package top.csy8888.likework.service.consumer;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.csy8888.likework.common.consts.RabbitConstants;
import top.csy8888.likework.dto.LikeDTO;
import top.csy8888.likework.entity.Like;
import top.csy8888.likework.entity.Post;
import top.csy8888.likework.mapper.LikeMapper;
import top.csy8888.likework.mapper.PostMapper;
import top.csy8888.likework.service.LikeService;
import top.csy8888.likework.service.PostService;

/**
 * @author CSY
 * @date 2025 - 10 - 12
 */
@Service
@Slf4j
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(name = RabbitConstants.QUEUE_NAME,durable = "false"),
        exchange = @Exchange(name = RabbitConstants.EXCHANGE_NAME,type = ExchangeTypes.DIRECT),
        key = RabbitConstants.ROUTING_KEY
))
@Transactional(rollbackFor = RuntimeException.class)
@RequiredArgsConstructor
public class LikeConsumerService {
    private final LikeMapper likeMapper;

    private final PostMapper postMapper;

    @RabbitHandler
    public void receiveLike(LikeDTO likeDTO) {
        // 添加点赞记录或删除点赞记录
        if (likeDTO.getLikeStatus()){
            Like like = new Like();
            BeanUtils.copyProperties(likeDTO,like);
            likeMapper.insert(like);
        }else {
            likeMapper.delete(likeDTO.getUserId(),likeDTO.getPostId());
        }

        Post post = new Post();
        BeanUtils.copyProperties(likeDTO,post);
        postMapper.updatePost(post);
    }
}
